package com.example.controller;

import com.example.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/file")
public class FileController {

    @GetMapping("/download")
    public Object download() throws Exception {
        System.out.println("下载");
        // 读取一个固定的文件，输入流只有一个核心方法：读取
        InputStream is = new
                FileInputStream("F:\\课堂\\高级Java框架项目开发\\课件\\第1章 初识MyBatis框架.pptx");
        byte[] bytes = is.readAllBytes(); // 内容
        is.close();
        // 构造响应头
        MultiValueMap<String, String> headers =
                new LinkedMultiValueMap<>();
        String filename = URLEncoder.encode("第1章 初识MyBatis框架.pptx",
                StandardCharsets.UTF_8);
        headers.add("Content-Disposition", "attachment; filename="
                + filename);
        /* 下载需要响应这个类的对象 */
        /* 需要3个部分，字节数组、头部信息的map、状态码 */
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @PostMapping("/upload")
    public Object upload(MultipartFile a) throws Exception {
        System.out.println(a);
        // 保存到磁盘
        a.transferTo(new File("F:\\" +
                a.getOriginalFilename()));
        return Result.success("上传成功");
    }
}
